package com.nj.dms.controller;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.nj.dms.bean.User;
import com.nj.dms.dao.UserDao;
import com.nj.dms.dao.impl.UserDaoImpl;

/**
 * 保存修改的用户信息
 */
@WebServlet("/SaveUser")
public class SaveUser extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获取客户端表单输入数据
		int id = new Integer(request.getParameter("id"));
		String name = request.getParameter("name");

		int year = new Integer(request.getParameter("year"));
		int month = new Integer(request.getParameter("month"));
		int day = new Integer(request.getParameter("day"));

		int branch = new Integer(request.getParameter("branch"));
		int sex = new Integer(request.getParameter("sex"));
		int type = new Integer(request.getParameter("type"));

		Date birthday = null;
		try {
			birthday = new SimpleDateFormat("yyyy-MM-dd").parse(year + "-" + month + "-" + day);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		// 将表单输入的数据放入User对象
		User user = new User();
		user.setId(id);
		user.setName(name);
		user.setBranch(branch);
		user.setSex(sex);
		user.setType(type);
		user.setBirthday(birthday);
		user.setUpdateDate(new Date());

		// 实例化一个UserDao类型的对象保存用户数据
		UserDao userDao = new UserDaoImpl();

		// 调用UserDao类型的用户增加方法addUser,保存用户数据
		if (userDao.saveUser(user)) {
			// 跳转到Userlist，获取用户信息后到userlist.jsp去显示用户列表
			// request.getRequestDispatcher("UserList").forward(request,response);

			response.sendRedirect("UserList");
		} else {

			request.getRequestDispatcher("UpdateUser?id=" + id).forward(request, response);
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
